package simplify.ur.life.rasberryswitch.util.ssh;

import java.io.InputStream;

import simplify.ur.life.rasberryswitch.util.Ut;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class SshConnection {

	JSch jsch;
	Session session;

	public SshConnection() {
		jsch = new JSch();
	}

	public void connect(String host, String user, String password) {
		try {
			session = jsch.getSession(user, host, 22);

			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			config.put("PreferredAuthentications",
                    "password,gssapi-with-mic,publickey,keyboard-interactive");

            session.setTimeout(15000);
			session.setPassword(password);						
			session.setConfig(config);

			session.connect();

		} catch (JSchException e) {
			Ut.e("SSH Connection:" + e.toString());
			Ut.d("SSH Credentials are:" + user+" | "+password);
			session = null;
		}
	}

	public void disconnect() {
		if (session != null) {
			session.disconnect();
		}
		session = null;
		Ut.e("SSH disconnected");
	}

	public boolean isConnected() {
		return session != null;
	}

	public String executeCommand(String command) {
		Channel channel = null;
		String output = "";
		try {
			channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(command);

			// channel.setInputStream(System.in);
			channel.setInputStream(null);

			// channel.setOutputStream(System.out);
			((ChannelExec) channel).setErrStream(System.err);

			InputStream in = channel.getInputStream();

			channel.connect();

			byte[] tmp = new byte[512];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, tmp.length);
					if (i < 0)
						break;
					output = new String(tmp, 0, i);
				}
				if (channel.isClosed()) {
					Ut.i(command + " - exit-status: " + channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(300);
				} catch (Exception ee) {
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (channel != null) {
				channel.disconnect();
			}
		}
		Ut.i(command + " - output: " + output);
		return output;
	}

}
